<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/dute_favicon_32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/dute_favicon_16x16.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <link rel="manifest" href="/images/manifest.json">
  <meta name="msapplication-config" content="/images/browserconfig.xml">
  <meta http-equiv="Cache-Control" content="no-transform">
  <meta http-equiv="Cache-Control" content="no-siteapp">
  <meta name="google-site-verification" content="mpI5dkydstZXl6UcDCppqktXK0bbvqdZ6LkZ3KNk4Iw">
  <meta name="baidu-site-verification" content="code-a1LksZX2Ds">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"whitestore.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="jvm是如何分配内存的">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解JVM - 对象分配内存">
<meta property="og:url" content="https://whitestore.top/2022/02/20/duixiangfenpei/index.html">
<meta property="og:site_name" content="爱看书的阿东">
<meta property="og:description" content="jvm是如何分配内存的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811220025.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210623223612.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811070946.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811073323.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811073640.png">
<meta property="og:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811075032.png">
<meta property="article:published_time" content="2022-02-20T12:28:31.000Z">
<meta property="article:modified_time" content="2023-07-16T06:28:09.271Z">
<meta property="article:author" content="阿东">
<meta property="article:tag" content="jvm">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811220025.png">

<link rel="canonical" href="https://whitestore.top/2022/02/20/duixiangfenpei/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>深入理解JVM - 对象分配内存 | 爱看书的阿东</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="爱看书的阿东" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">爱看书的阿东</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">赐他一块白色石头，石头上写着新名</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>站点地图</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://whitestore.top/2022/02/20/duixiangfenpei/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="阿东">
      <meta itemprop="description" content="随遇而安">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="爱看书的阿东">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          深入理解JVM - 对象分配内存
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2022-02-20 20:28:31" itemprop="dateCreated datePublished" datetime="2022-02-20T20:28:31+08:00">2022-02-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-07-16 14:28:09" itemprop="dateModified" datetime="2023-07-16T14:28:09+08:00">2023-07-16</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JVM/" itemprop="url" rel="index"><span itemprop="name">JVM</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2022/02/20/duixiangfenpei/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2022/02/20/duixiangfenpei/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.9k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>4 分钟</span>
            </span>
            <div class="post-description">jvm是如何分配内存的</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="深入理解JVM-对象分配内存"><a href="#深入理解JVM-对象分配内存" class="headerlink" title="深入理解JVM - 对象分配内存"></a>深入理解JVM - 对象分配内存</h1><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>​    这一节我们来讨论对象分配内存的细节，这一块的内容相对比较简单，但是也是比较重要的内容，最后会总结书里面的OOM的溢出案例，在过去的文章已经讲到过不少类似的情况。</p>
<h1 id="思维导图："><a href="#思维导图：" class="headerlink" title="思维导图："></a>思维导图：</h1><p>地址：<span class="exturl" data-url="aHR0cHM6Ly93d3cubXVidWNtLmNvbS9kb2MvNm5GVWNiRW4tM0I=" title="https://www.mubucm.com/doc/6nFUcbEn-3B">https://www.mubucm.com/doc/6nFUcbEn-3B<i class="fa fa-external-link"></i></span></p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811220025.png" alt=""></p>
<h1 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h1><ol>
<li>讲述对象分配内存的方式：“指针碰撞”和“空闲列表”的实现方式</li>
<li>对象分配中使用了哪些方法，当出现并发分配使用什么方式进行处理的。</li>
<li>对象的访问方式有哪些，访问的过程的优劣对比</li>
<li>对象在内存当中的布局，分为三个大类，需要重点掌握对象头的部分</li>
<li>实战OOM的内容，这部分适合实战的时候再看。</li>
</ol>
<a id="more"></a>



<h1 id="对象的创建"><a href="#对象的创建" class="headerlink" title="对象的创建"></a>对象的创建</h1><p>​    对象什么时候会创建的，虽然很多情况下我们会声明比如<code>public static final</code>然而实际上这些公开常量不使用的时候其实并不会占用内存，只有在 <strong>真正被使用的情况下才会通过类加载器加载进内存空间</strong>。这里需要注意一个非常重要的点就是，对象一旦被创建就可以<strong>确定对象占用的内存大小</strong>，这一步在类加载器的阶段会完成，至于类加载器的具体细节，将会在后续的文章进行讲述。</p>
<p>​    对象创建的过程可以简述为：检查是否在常量池当中找到引用，如果没有引用，执行类加载的过程。</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210623223612.png" alt=""></p>
<h2 id="分配方式"><a href="#分配方式" class="headerlink" title="分配方式"></a>分配方式</h2><p>​    既然知道了对象的创建，那么此时我们需要了解对象是如何分配的，一般情况下有两种主流的方案：“指针碰撞”和“空闲列表”。</p>
<p>​    指针碰撞：假设堆内存是绝对的规整的（前提），把所有使用过的内存放到一遍，把没有使用过多内存放在另一边，中间放着一个指针作为指示器，如果出现内存分配，则将分界线往空闲的那一边挪动即可。简单的画图理解如下：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811070946.png" alt=""></p>
<p>​    空闲列表：如果内存不是规整而是交错的情况下使用这一种算法，如果内存不是规整的这时候虚拟机需要维护一个空闲列表记录那些空间是可用的，在对象分配的时候需要找到一块足够大的空间进行使用，然而如果没有足够大的空间，这时候就需要使用垃圾收集器进行收集之后，在根据内存的实际情况采用指针碰撞还是空闲列表。</p>
<h3 id="如何判断用哪种算法？"><a href="#如何判断用哪种算法？" class="headerlink" title="如何判断用哪种算法？"></a>如何判断用哪种算法？</h3><p>​    这两个对象分配的算法由堆决定是否规整决定是否使用，但是堆是否规则又和<strong>垃圾收集器</strong>有关，如果垃圾收集器没有使用标记整理这种算法，通常情况下使用空闲列表，而如果使用了，毫无疑问此时的内存空间是十分规整的，从而会使用指针碰撞的算法。</p>
<p>​    另外，指针碰撞的效率明显是要比空闲列表的算法要高不少。</p>
<h3 id="并发分配的处理办法"><a href="#并发分配的处理办法" class="headerlink" title="并发分配的处理办法"></a>并发分配的处理办法</h3><p>​    这里还有一个问题，如果此时出现两个对象并发进行创建的时候，出现的使用同一块内存进行分配的情况，这种情况下JVM又有两种处理方式： <strong>分配内存空间的动作进行同步处理</strong>（意思就是说吧整个分配过程同步），改进的方式是使用<strong>CAS加上失败重试的机制保证更新操作的原子性</strong>。</p>
<p>​    除此之外，还有一种方法是在分配对象是在不同的线程空间中进行的，每一个线程在JAVA堆当中分配一小块内存（可以理解为线程的专属空间），这一块内存也叫做“<strong>本地线程缓冲</strong>”，那个线程需要内存就分配到哪一个线程缓冲<strong>（TLAB）</strong>，只有本地线程缓冲用完了，才需要使用同步锁锁住。</p>
<blockquote>
<p>提示：JVM通过使用 <strong>-XX:+/-UseTLAB</strong> 决定是否开启</p>
</blockquote>
<p>​    毫无疑问，JVM同时使用了这两种方式，大致的方式是在本地线程缓冲池足够的时候，会使用第二种方式，但是一旦TLAB用完，就会采用CAS锁失败重试锁进行对象的分配，这样可以最大限度的减少线程停顿和等待的时间。</p>
<h2 id="访问方式"><a href="#访问方式" class="headerlink" title="访问方式"></a>访问方式</h2><p>​    了解了对象是如何分配的，这里肯定也会想知道<strong>栈是如何访问堆上的内存</strong>的，最简单的理解是在栈上分配一个引用，这个引用本质上是一个 <strong>指针</strong>，在JAVA当中叫做使用<strong>栈上的reference 操作堆上的数据</strong>，这个指针指向堆空间对象引用的地址，这样我们可以操作栈上的引用就可以操作堆内存的空间。最后，<strong>对象的访问方式由虚拟机决定</strong>。</p>
<h3 id="访问方式的实现"><a href="#访问方式的实现" class="headerlink" title="访问方式的实现"></a>访问方式的实现</h3><p>​    访问方式的实现由两种方式：<strong>句柄访问和直接访问</strong>。下面来分别访问一下这两种方式的差别。</p>
<p>​    句柄访问：句柄访问的方式会在堆中划分一块内存作为句柄池，引用中存储的是句柄的地址，句柄中包含了对象的实例数据和类型数据等等具体信息的<strong>地址</strong>。注意这里是实例数据的地址而不是实例数据哦，用画图表示如下：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811073323.png" alt=""></p>
<p>​    直接指针：更为简单好理解，栈上引用指向的就是对象实例数据的地址，访问对象不需要一次间接访问的开销。</p>
<p>​    <img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811073640.png" alt=""></p>
<h3 id="优劣对比"><a href="#优劣对比" class="headerlink" title="优劣对比"></a>优劣对比</h3><p>​    句柄：</p>
<ul>
<li>垃圾清理之后，只需要改变实例指针的数据不需要改变reference。</li>
</ul>
<p>​    直接指针：</p>
<ul>
<li><p>必须考虑对象实例数据的存放问题（设计）</p>
</li>
<li><p>可以减少一次指针访问的内存开销同时减少指针定位的开销</p>
</li>
</ul>
<p>​    我们知道了对象是如何访问的，现在我们再来看下，对象创建之后的内部结构如何。</p>
<h1 id="对象在内存当中布局"><a href="#对象在内存当中布局" class="headerlink" title="对象在内存当中布局"></a>对象在内存当中布局</h1><p>​    对象的存储布局可以分为三个部分：对象头、实例数据、对齐填充。</p>
<p>​    </p>
<h2 id="对象头："><a href="#对象头：" class="headerlink" title="对象头："></a>对象头：</h2><p>​    对象头分为两类：第一类是存储自身的运行时候的数据（MarkWord），第二类是类型指针，下面来分贝说明：</p>
<p>​    第一类存储的是对象运行时候的数据，包含内容有 哈希码、GC分代年龄、锁状态标志，线程持有锁等等内容，这一块内存在设计上根据不同虚拟机的位数分别占用32位和64位的空间大小，官方称这一块空间为“MarkWord”。注意Markword使用的是动态定义的数据结构，方便在极小的空间存储尽可能多的内容。</p>
<h3 id="Markword的分布内容："><a href="#Markword的分布内容：" class="headerlink" title="Markword的分布内容："></a>Markword的分布内容：</h3><p>​    假设在32位的虚拟机当中，<strong>对象未被同步锁定的状态</strong>下，他的结构如下，这里需要注意的是对象分代年龄这一个面试考点：</p>
<p><img src="https://gitee.com/lazyTimes/imageReposity/raw/master/img/20210811075032.png" alt=""></p>
<p>​    第二类则是<strong>类型指针</strong>，通过类型指针类确定他的实例数据是哪一个类的实例，如果是数组的结构，还需要额外维护一块内容来标记数组的长度。到了这里我们暂停一下，在之前文章当中他提到过，我们分配字节数组的大小实际上JVM会耗费更多的内存空间进行存储，这里的的对象头就是消耗了一部分。</p>
<p>​    </p>
<h2 id="实例数据"><a href="#实例数据" class="headerlink" title="实例数据"></a>实例数据</h2><p>​    第二部分是实例数据的部分，这个部分才是真正的存储数据的地方，保存了我们在程序代码里面定义的各种字段内容。</p>
<p>​    另外，虚拟机的默认分配顺序为：</p>
<ul>
<li>基础类型：longs/double 向下分配</li>
<li><strong>对象最后分配</strong></li>
</ul>
<h2 id="对象补齐"><a href="#对象补齐" class="headerlink" title="对象补齐"></a>对象补齐</h2><p>​    最后一部分是对象填充的内容，基本没有多少含义，仅仅作为补齐占位符使用，同时为了保证对象的对齐标准，<strong>对象必须是8的整数倍</strong>。</p>
<blockquote>
<p>提示：这里有个问题，为什么Hotspot的虚拟机起始字节是8的整数倍？</p>
<p>因为对象头被设计为刚好是8个倍数，这样就不需要对齐补齐，但是一旦不够会根据8的次方进行补齐的操作。</p>
</blockquote>
<h1 id="实战OOM"><a href="#实战OOM" class="headerlink" title="实战OOM"></a>实战OOM</h1><p>​    其实这部分已经在之前的文章已经提到过了，这些内容适合自己解决JVM问题的时候翻一翻，简单做一下笔记即可。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line">1. java堆溢出</span><br><span class="line">    实例参数</span><br><span class="line">        -Xmas 20m</span><br><span class="line">        -xmx 20m</span><br><span class="line">        -xx+HeapDumpOnOutOfMemoryError</span><br><span class="line">    异常</span><br><span class="line">        java heap dump</span><br><span class="line">    处理方式</span><br><span class="line">        如果是内存泄漏，gcroot，引用链上看对应gc的异常链信息</span><br><span class="line">        检查（-xmx 与 -xmx）设置</span><br><span class="line">            看参数设置</span><br><span class="line">            对象生命周期过长，持有状态过长</span><br><span class="line">    排查工具</span><br><span class="line">        eclipse：eclipse memory analyze</span><br><span class="line">2. 本地方法栈溢出</span><br><span class="line">    ⚠️hotspot 本质上不区分虚拟机栈与本地方法栈。同时hotspot 不支持动态扩展。</span><br><span class="line">    问题</span><br><span class="line">        本地方法栈不支持动态扩展出现oom</span><br><span class="line">        如何确定栈的最小值</span><br><span class="line">            操作系统的内存分页大小决定</span><br><span class="line">    异常</span><br><span class="line">        无法容纳新的栈帧。导致soe异常</span><br><span class="line">    如何验证</span><br><span class="line">        使用-Xss 减少栈内存空间</span><br><span class="line">        定义大量本地变量。增大方法帧中的变量表长度</span><br><span class="line">        some个人实验</span><br><span class="line">            stack length 981</span><br><span class="line">            定义大量的栈帧（变量）</span><br><span class="line">    结论</span><br><span class="line">        无论是栈帧太大还是虚拟机太小，新的栈帧内存无法分配时候，soe异常</span><br><span class="line">        java堆与方法区最大值计算</span><br><span class="line">            单进程最大内存限制位2gb</span><br><span class="line">                最大堆容量</span><br><span class="line">                方法区容量</span><br><span class="line">                程序计数器</span><br><span class="line">                虚拟机消耗</span><br><span class="line">                直接内存</span><br><span class="line">            栈帧空间越大，越容易耗尽内存</span><br><span class="line"></span><br><span class="line">3. 方法区和运行时常量池溢出</span><br><span class="line">    发展历史</span><br><span class="line">        Jdk6</span><br><span class="line">            -xx:perm size 和 -xx:bumper size 限制永久代大小</span><br><span class="line">                溢出结果：Permgen space</span><br><span class="line">        Jdk7</span><br><span class="line">            由于永久代放到堆上，所以出现引用一致</span><br><span class="line">        jdk8</span><br><span class="line">            和jdk7一致</span><br><span class="line">            jdk8防止创建新类型做一些预防</span><br><span class="line">                -xx: maxMetaSpaceSize: 元空间最大值默认为-1</span><br><span class="line">                -xx: metaspacesize: 元空间初始大小</span><br><span class="line">                -xx minMetaSpaceFreeRatio：垃圾收集后最小元空间乘百分比</span><br><span class="line">    案例</span><br><span class="line">        为什么java会出现两个false</span><br><span class="line">            a这个字符在intern当中并不是首次遇到</span><br><span class="line"></span><br><span class="line">        如何让方法区溢出</span><br><span class="line">            Jdk8元空间与堆共享方法区，不再那么容易溢出</span><br><span class="line">            jdk7可以用大量代理对象出现方法区溢出</span><br><span class="line"></span><br><span class="line">4. 本地直接内存溢出</span><br><span class="line">     异常情况</span><br><span class="line">        Oom异常：和普通的oom情况不一样</span><br><span class="line">            如果dump出来的文件很小，程序间接或者直接使用nio可以考虑直接内存原因</span><br><span class="line">    默认是Ljava 堆最大值[ -xmx 一致]</span><br><span class="line">        用-xx: maxDirectMemorySize 指定直接内存如何溢出</span><br><span class="line">            使用unsafe.allocateMemory 不断申请内存</span><br></pre></td></tr></table></figure>

<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>​    通过对象的创建，我们了解了对象的两种分配方式，指针碰撞和空闲列表，同时我们了解了他们在不同的垃圾收集器下使用的分配方式不同，另外我们了解了并发创建对象的问题，使用CAS以及TLAB本地缓存的方式进行处理。</p>
<p>​    接着我们了解了对象的访问方式，拥有句柄和直接访问两种方式，接着我们对比了这两者的差别，最后我们了解了对象的具体结构。</p>
<h1 id="写在最后"><a href="#写在最后" class="headerlink" title="写在最后"></a>写在最后</h1><p>​    对象分配内存这一块内容比较简单，只要掌握对象创建内容以及相关的布局重点即可。</p>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>阿东
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://whitestore.top/2022/02/20/duixiangfenpei/" title="深入理解JVM - 对象分配内存">https://whitestore.top/2022/02/20/duixiangfenpei/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLzQuMC96aC1DTg=="><i class="fa fa-fw fa-creative-commons"></i>BY-NC</span> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JVM/" rel="tag"># JVM</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2022/02/20/changtui/" rel="prev" title="《长腿叔叔》读书笔记">
      <i class="fa fa-chevron-left"></i> 《长腿叔叔》读书笔记
    </a></div>
      <div class="post-nav-item">
    <a href="/2022/02/20/riqiapi/" rel="next" title="【Java】JAVA8 实战 - 日期API">
      【Java】JAVA8 实战 - 日期API <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#深入理解JVM-对象分配内存"><span class="nav-number">1.</span> <span class="nav-text">深入理解JVM - 对象分配内存</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">2.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#思维导图："><span class="nav-number">3.</span> <span class="nav-text">思维导图：</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#概述"><span class="nav-number">4.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#对象的创建"><span class="nav-number">5.</span> <span class="nav-text">对象的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#分配方式"><span class="nav-number">5.1.</span> <span class="nav-text">分配方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#如何判断用哪种算法？"><span class="nav-number">5.1.1.</span> <span class="nav-text">如何判断用哪种算法？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#并发分配的处理办法"><span class="nav-number">5.1.2.</span> <span class="nav-text">并发分配的处理办法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#访问方式"><span class="nav-number">5.2.</span> <span class="nav-text">访问方式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#访问方式的实现"><span class="nav-number">5.2.1.</span> <span class="nav-text">访问方式的实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优劣对比"><span class="nav-number">5.2.2.</span> <span class="nav-text">优劣对比</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#对象在内存当中布局"><span class="nav-number">6.</span> <span class="nav-text">对象在内存当中布局</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#对象头："><span class="nav-number">6.1.</span> <span class="nav-text">对象头：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Markword的分布内容："><span class="nav-number">6.1.1.</span> <span class="nav-text">Markword的分布内容：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实例数据"><span class="nav-number">6.2.</span> <span class="nav-text">实例数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#对象补齐"><span class="nav-number">6.3.</span> <span class="nav-text">对象补齐</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实战OOM"><span class="nav-number">7.</span> <span class="nav-text">实战OOM</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">8.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#写在最后"><span class="nav-number">9.</span> <span class="nav-text">写在最后</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">阿东</p>
  <div class="site-description" itemprop="description">随遇而安</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">239</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">36</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2xhenlUaW1lcw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lazyTimes"><i class="fa fa-fw fa-github"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjEwOTc0ODM1MDhAcXEuY29t" title="E-Mail → mailto:1097483508@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly93d3cuNTJwb2ppZS5jbi9ob21lLnBocD9tb2Q9c3BhY2UmdWlkPTE0OTc3MTgmZG89dGhyZWFkJnZpZXc9bWUmZnJvbT1zcGFjZQ==" title="https:&#x2F;&#x2F;www.52pojie.cn&#x2F;home.php?mod&#x3D;space&amp;uid&#x3D;1497718&amp;do&#x3D;thread&amp;view&#x3D;me&amp;from&#x3D;space">吾爱破解</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9qdWVqaW4uaW0vdXNlci8yOTk5MTIzNDUyNjI2MzY2" title="https:&#x2F;&#x2F;juejin.im&#x2F;user&#x2F;2999123452626366">掘金</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9zZWdtZW50ZmF1bHQuY29tL3UvbGF6eXRpbWVz" title="https:&#x2F;&#x2F;segmentfault.com&#x2F;u&#x2F;lazytimes">思否</span>
        </li>
    </ul>
  </div>

      </div>

      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://adong-picture.oss-cn-shenzhen.aliyuncs.com/adong/wechat_channel.jpg">
      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">阿东</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">2m</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">29:50</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'qMUpEEvBgXaMDD1b0ftgi9xr-gzGzoHsz',
      appKey     : 'UCdfT4Rfih6MO6y8DI4fstf6',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
